import { http } from "@/utils/http";
import { getToken, formatToken } from "@/utils/auth";
export type FileInfoResult = {
  code?: number;
  data?: FileInfoVO;
  message?: string;
  [property: string]: any;
};

export type FileInfoVO = {
  id: string;
  fileName: string;
  fileUrl: string;
  fileSize: number;
  fileType: string;
  createTime?: string;
  [property: string]: any;
};
export const uploadFileApi = async formData => {
  // const queryString = handleQueryParams(queryParams); // 建议提取为公共方法
  return http.request<FileInfoResult>("post", `/files/upload`, {
    data: formData,
    headers: {
      "Content-Type": "multipart/form-data" // 必须显式设置
    },
    onUploadProgress: progressEvent => {
      const percent = Math.round(
        (progressEvent.loaded * 100) / progressEvent.total
      );
      console.log(`上传进度: ${percent}%`);
    }
  });
};
export const uploadAvatarApi = async (
  file: File,
  queryParams: Record<string, string>,
  filename
) => {
  console.log(file);
  const queryString = handleQueryParams(queryParams); // 建议提取为公共方法
  const formData = new FormData();
  formData.append("file", file);
  return http.request<FileInfoResult>("post", `/files/upload?${queryString}`, {
    data: formData,
    headers: {
      "Content-Type": "multipart/form-data" // 必须显式设置
    },
    onUploadProgress: progressEvent => {
      const percent = Math.round(
        (progressEvent.loaded * 100) / progressEvent.total
      );
      console.log(`上传进度: ${percent}%`);
    }
  });
};
// 建议新增公共方法处理查询参数
function handleQueryParams(params: Record<string, string>) {
  return Object.entries(params)
    .map(
      ([key, value]) =>
        `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
    )
    .join("&");
}
export const uploadFile2 = async (
  file: File,
  queryParams: Record<string, string>
) => {
  const formData = new FormData();
  formData.append("file", file);
  // formData.append('filename', 'example.jpg');
  // formData.append('filetype', 'png');
  const data = getToken();
  const queryString = Object.entries(queryParams)
    .map(
      ([key, value]) =>
        `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
    )
    .join("&");

  const url = `api/files/upload`;
  console.log(data.accessToken);
  const response = await fetch(url, {
    method: "POST",
    headers: {
      // 关键步骤：添加 Authorization 头，带上 Bearer 前缀和 JWT Token
      Authorization: `Bearer ${data.accessToken}`
      // 注意：Content-Type 不需要手动设置，FormData 会自动处理并添加正确的 multipart/form-data
    },
    body: formData
  });

  return response.json() as Promise<FileInfoResult>;
};
// 上传单个文件
export const uploadFile1 = (file: File, queryParams: FileUploadQuery) => {
  const formData = new FormData();
  formData.append("file", file);
  formData.append("filename", "example.jpg");
  formData.append("filetype", "png");

  const queryString = Object.entries(queryParams)
    .map(
      ([key, value]) =>
        `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
    )
    .join("&");

  const url = `/files/upload?${queryString}`;

  return http.request<Result<FileInfoVO>>("post", url, {
    data: formData,
    headers: { "Content-Type": "multipart/form-data" }
  });
};

// 批量上传文件
export const batchUpload = (
  data: FormData,
  queryParams: Record<string, string>
) => {
  const queryString = Object.entries(queryParams)
    .map(
      ([key, value]) =>
        `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
    )
    .join("&");

  const url = `/files/batch-upload?${queryString}`;

  return http.request<FileInfoResult>("post", url, {
    data,
    headers: { "Content-Type": "multipart/form-data" }
  });
};

// 下载文件（根据文件ID）
export const downloadFile = (filePath: string) => {
  return http.request<Blob>("get", `/files/download/${filePath}`, {
    responseType: "blob"
  });
};

// 删除文件
export const deleteFile = (fileId: string) => {
  return http.request<FileInfoResult>("delete", `/files/${fileId}`);
};

// 获取文件信息
export const getFileInfo = (fileId: string) => {
  return http.request<FileInfoResult>("get", `/files/info/${fileId}`);
};

// 新增查询参数类型
export interface FileUploadQuery {
  [key: string]: string | undefined;
}
